class WebSocketClient {
  constructor(url, options = {}) {
    this.url = url;
    this.options = options;
    this.reconnectCount = 0;
    this.maxReconnectAttempts = 5;
    this.token = '';
    this.socketTask = null;
  }

  connect() {
    try {
      if (!this.token) {
        console.error('Token is empty');
        return;
      }

      const url = `${this.url}?token=${encodeURIComponent(this.token)}`;
      
      this.socketTask = wx.connectSocket({
        url: url,
        header: {
          'Authorization': this.token
        },
        success: () => {
          console.log('WebSocket连接成功');
        },
        fail: (error) => {
          console.error('创建WebSocket连接失败:', error);
          this.reconnect();
        }
      });

      this.socketTask.onOpen(() => {
        console.log('WebSocket连接已打开');
        this.reconnectCount = 0;
      });

      this.socketTask.onClose(() => {
        console.log('WebSocket连接已关闭');
        this.reconnect();
      });

      this.socketTask.onError((error) => {
        console.error('WebSocket错误:', error);
        this.reconnect();
      });

      this.socketTask.onMessage((res) => {
        try {
          const data = JSON.parse(res.data);
          console.log('收到消息:', data);
          // 处理消息
        } catch (error) {
          console.error('解析消息失败:', error);
        }
      });

    } catch (error) {
      console.error('创建WebSocket连接失败:', error);
      this.reconnect();
    }
  }

  reconnect() {
    if (this.reconnectCount >= this.maxReconnectAttempts) {
      console.log('WebSocket重连次数超过最大限制，停止重连');
      return;
    }

    this.reconnectCount++;
    console.log(`尝试重新连接... (${this.reconnectCount}/${this.maxReconnectAttempts})`);

    setTimeout(() => {
      this.connect();
    }, 3000);
  }

  setToken(token) {
    this.token = token;
  }

  close() {
    if (this.socketTask) {
      this.socketTask.close({
        success: () => {
          console.log('WebSocket连接已主动关闭');
        }
      });
    }
  }
}

export default WebSocketClient;